<?php
/**
 * Created by PhpStorm.
 * User: u
 * Date: 2019/4/8
 * Time: 14:56
 */

namespace common\logics\principalcash;

use common\widgets\Tool;
use Yii;
use yii\base\BaseObject;

class PrincipalCashLogic extends BaseObject implements IPrincipalCash
{
    /** @var \common\sources\read\principalcash\PrincipalCashAccess  $RPrincipalCashAccess ***/
    private $RPrincipalCashAccess;
    /** @var \common\sources\write\principalcash\PrincipalCashAccess  $WPrincipalCashAccess ***/
    private $WPrincipalCashAccess;
    /** @var \common\sources\read\taskorder\TaskOrderAccess  $RTaskOrderAccess ***/
    private $RTaskOrderAccess;
    /** @var \common\sources\write\taskorder\TaskOrderAccess $WTaskOrderAccess ***/
    private $WTaskOrderAccess;
    /** @var \common\sources\read\buyuser\BuyUserAccess  $RBuyUserAccess ***/
    private $RBuyUserAccess;
    /** @var \common\sources\read\buyuser\BuyUserAcountAccess  $RBuyUserAcountAccess ***/
    private $RBuyUserAcountAccess;
    /** @var \common\sources\write\buyuser\BuyUserAcountAccess  $WBuyUserAcountAccess ***/
    private $WBuyUserAcountAccess;
    /** @var \common\sources\read\bank\BankAccess  $RBankAccess  ***/
    private $RBankAccess;
    /** @var \common\sources\write\depositrecord\DepositRecordAccess $WDepositRecordAccess ***/
    private $WDepositRecordAccess;

    public function init()
    {
        $this->RPrincipalCashAccess = Yii::$container->get("RPrincipalCashAccess");
        $this->WPrincipalCashAccess = Yii::$container->get("WPrincipalCashAccess");
        $this->RTaskOrderAccess = Yii::$container->get("RTaskOrderAccess");
        $this->WTaskOrderAccess = Yii::$container->get("WTaskOrderAccess");
        $this->RBuyUserAccess = Yii::$container->get("RBuyUserAccess");
        $this->RBuyUserAcountAccess = Yii::$container->get("RBuyUserAcountAccess");
        $this->WBuyUserAcountAccess = Yii::$container->get("WBuyUserAcountAccess");
        $this->RBankAccess = Yii::$container->get("RBankAccess");
        $this->WDepositRecordAccess = Yii::$container->get("WDepositRecordAccess");
        parent::init(); // TODO: Change the autogenerated stub
    }

    public function getList($data)
    {
        if(empty($data['buy_id']))
        {
            return Tool::returnJson([],401,"买手用户id不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],402,"安全码不能为空");
        }
        if(md5($data['buy_id']) != $data['safetyCode'])
        {
            return Tool::returnJson([],403,"安全码不正确");
        }
        $count = $this->RPrincipalCashAccess->getPrincipalCashCount($data);
        $list = [];
        if($count >0)
        {
            $list = $this->RPrincipalCashAccess->getPrincipalCashList($data);
            foreach ($list as &$item)
            {
                $item['create_time'] = isset($item['create_time']) ? date('Y-m-d H:i:s',$item['create_time']) : '';
                $item['status_name'] = isset($item['status']) ? Yii::$app->params['principal_cash_status'][$item['status']] : "";
                $item['task_order'] = $this->RTaskOrderAccess->getTaskOrderByIds($item['task_order_ids']);
                if(count($item['task_order']) >0)
                {
                    foreach ($item['task_order'] as &$task_order)
                    {
                        $task_order['create_time'] = isset($task_order['create_time']) ? date('Y-m-d H:i:s',$task_order['create_time']): '';
                    }
                }

            }
        }
        return Tool::returnJson([
            "list" => $list,
            "count" => $count,
            "page_num" => $data['page_num'],
        ],200,"成功");
    }

    public function revoke($data)
    {
        if(empty($data['buy_id']))
        {
            return Tool::returnJson([],401,"买手id不能为空");
        }
        if(empty($data['principal_cash_id']))
        {
            return Tool::returnJson([],402,"申请提现id不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],403,"安全码不能为空");
        }
        if(md5($data['buy_id'].$data['principal_cash_id']) != $data['safetyCode'])
        {
            return Tool::returnJson([],405,"安全码不正确");
        }
        $principal_cash = $this->RPrincipalCashAccess->getPrincipalCashById($data['principal_cash_id']);
        if(empty($principal_cash))
        {
            return Tool::returnJson([],406,"你申请的本金提现记录不存在");
        }
        if($principal_cash['status'] !=1)
        {
            return Tool::returnJson([],407,"非待审核中的提现记录不能取消");
        }
        $buyUser = $this->RBuyUserAccess->getBuyUserInfo($data['buy_id']);
        if(empty($buyUser))
        {
            return Tool::returnJson([],408,"买手用户不存在");
        }
        $buy_account = $this->RBuyUserAcountAccess->getBuyUserAccount($data['buy_id']);
        if(empty($buy_account))
        {
            return Tool::returnJson([],409,"买手账号信息不存在");
        }

        $transaction = Yii::$app->db->beginTransaction();
        try{
            $cash_arr = [
                "status" => 6,
                "id" => $data['principal_cash_id']
            ];
            $res = $this->WPrincipalCashAccess->modifyPrincipalCash($cash_arr);
            if($res)
            {
                $arr = [
                    "remain_funds" => number_format($buy_account['remain_funds'] + $principal_cash['money'],2,'.',''),
                    "freezing_funds" => number_format($buy_account['freezing_funds'] - $principal_cash['money'],2,'.',''),
                    "buy_id" => $data['buy_id'],
                ];
                $buy_res = $this->WBuyUserAcountAccess->modifyPrincipalUserAccount($arr);
                if($buy_res)
                {
                    //修改子订单状态
                    $this->WTaskOrderAccess->modifyTaskOrderRevoke(['order_status' => 8,"task_order_arr"=> explode(',',$principal_cash['task_order_ids'])]);
                    //增加本金记录
                    $buy_deposit_arr = [
                        "type" =>3,
                        "buy_id" => $data['buy_id'],
                        "expend" => 0,
                        "income" => $principal_cash['money'],
                        "balance" =>  number_format($buy_account['remain_funds'] + $principal_cash['money'],2,'.',''),
                        "freeze_change" => -$principal_cash['money'],
                        "freeze_balance" => number_format($buy_account['freezing_funds'] - $principal_cash['money'],2,'.',''),
                        "remark" => "撤销本金提现返还提现本金"
                    ];
                    $res_principal = $this->WDepositRecordAccess->addDepositRecord($buy_deposit_arr);
                    if(!$res_principal)
                    {
                        $transaction->rollBack();
                        return Tool::returnJson([],411,"撤销本金提现返还提现本金失败");
                    }
                    $transaction->commit();
                    return Tool::returnJson([],200,"成功");
                }
                $transaction->rollBack();
                return Tool::returnJson([],412,"撤销失败");
            }
            $transaction->rollBack();
            return Tool::returnJson([],413,"撤销失败");
        }catch (\Exception $e)
        {
            $transaction->rollBack();
            return Tool::returnJson([],5000,"撤销异常".$e->getMessage());
        }
    }
    //申请提现
    public function applyCash($data)
    {
        if(empty($data['buy_id']))
        {
            return Tool::returnJson([],401,"买手id不能为空");
        }
        if(empty($data['task_order_ids']))
        {
            return Tool::returnJson([],402,"任务订单id不能为空");
        }
        if(!is_array($data['task_order_ids']))
        {
            return Tool::returnJson([],403,"任务订单id必须是数组");
        }
        if(empty($data['pay_pwd']))
        {
            return Tool::returnJson([],405,"买手id不能为空");
        }
        if(empty($data['money']))
        {
            return Tool::returnJson([],406,"申请提现金额不能为空");
        }
        $buyer = $this->RBuyUserAccess->getBuyUserInfo($data['buy_id']);
        if(empty($buyer))
        {
            return Tool::returnJson([],407,"买手账号不存在");
        }
        $buy_account = $this->RBuyUserAcountAccess->getBuyUserAccount($data['buy_id']);
        if(empty($buy_account))
        {
            return Tool::returnJson([],408,"买手账号信息不存在");
        }
        if(empty($buyer['paypwd']) || $buyer['is_pay'] == 0)
        {
            return Tool::returnJson([],409,"没有设置提现密码");
        }
        //验证密码
        if (!Yii::$app->security->validatePassword($data['pay_pwd']."", $buyer['paypwd'])) {
            return Tool::returnJson([], 410, '提现密码错误');
        }
        if($buy_account['remain_funds'] < $data['money'])
        {
            return Tool::returnJson([],411,"提现金额大于本金余额");
        }
        $buy_bank_count = $this->RBankAccess->getBuyUserBankStatusAccount($data['buy_id']);
        if(empty($buy_bank_count))
        {
            return Tool::returnJson([],412,"提现信息不存在");
        }
        //判断子订单是否可用提现
        $task_order_arr = $this->RTaskOrderAccess->getTaskOrderByStatusIds(implode(',',$data['task_order_ids']));
        if(count($task_order_arr))
        {
            $task_arr = array_column($task_order_arr,"order_status");
            $task_status = array_unique($task_arr);
            if(!(count($task_status) == 1 && $task_status[0] == 8))
            {
                return Tool::returnJson([],412,"非可提现子订单不能提现");
            }
        }
        //提现操作
        $transaction = Yii::$app->db->beginTransaction();
        $cash_num = "ST".date('YmdHis',time()).rand(1000,9999);
        try{
            $cash_arr = [
                "buy_id" => $data['buy_id'],
                "cash_num" => $cash_num,
                "money" => $data['money'],
                'cash_money' => $data['money'] <1000 ? number_format($data['money']-1,2,".",""):$data['money'],
                "task_order_ids" => implode(',',$data['task_order_ids']),
                "status" => 1,
                "remark" => "银行到账预计需要1-3个工资日，请等待转账",
                "real_name" => $buy_bank_count['real_name'],
                "card_num" => $buy_bank_count['cardnum'],
            ];
            $res = $this->WPrincipalCashAccess->addPrincipalCash($cash_arr);
            if($res)
            {
                //账号可用余额冻结
                $buy_arr = [
                    "remain_funds" =>number_format( $buy_account['remain_funds'] - $data['money'],2,".",""),
                    "freezing_funds" => number_format($buy_account['freezing_funds'] + $data['money'],2,".",""),
                    "buy_id" => $data['buy_id']
                ];
                $res_buy = $this->WBuyUserAcountAccess->modifyPrincipalUserAccount($buy_arr);
                if($res_buy)
                {
                    //修改子订单状态
                    $task_order_res = $this->WTaskOrderAccess->modifyTaskOrderApply(['order_status' => 12,"task_order_ids"=>$data['task_order_ids']]);
                    if(!$task_order_res)
                    {
                        $transaction->rollBack();
                        return Tool::returnJson([],413,"提现失败");
                    }
                    $deposit_arr = [
                        "type" => 2,
                        "expend" => number_format($data['money'],2,".",""),
                        "income" => 0,
                        "balance" => number_format( $buy_account['remain_funds'] - $data['money'],2,".",""),
                        'freeze_change' => number_format($data['money'],2,".",""),
                        "freeze_balance" => number_format($buy_account['freezing_funds'] + $data['money'],2,".",""),
                        "remark" => "买手提现任务扣减本金-".$data['money'],
                        "buy_id" => $data['buy_id']
                    ];
                    $res_deposit = $this->WDepositRecordAccess->addDepositRecord($deposit_arr);
                    if(!$res_deposit)
                    {
                        $transaction->rollBack();
                        return Tool::returnJson([],413,"手提现任务扣减本金记录失败");
                    }
                    $transaction->commit();
                    return Tool::returnJson([],200,"成功");
                }
                $transaction->rollBack();
                return Tool::returnJson([],413,"提现失败");
            }
            $transaction->rollBack();
            return Tool::returnJson([],413,"提现失败");
        }catch (\Exception $e)
        {
            $transaction->rollBack();
            return Tool::returnJson([],5000,"提现异常".$e->getMessage());
        }
    }
    //可提现列表
    public function getAvaPrincipalList($data)
    {
        if(empty($data['buy_id']))
        {
            return Tool::returnJson([],401,"买手用户id不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],402,"安全码不能为空");
        }
        if(md5($data['buy_id'].$data['apply_status']) != $data['safetyCode'])
        {
            return Tool::returnJson([],403,"安全码不能为空");
        }
        $buyer = $this->RBuyUserAccess->getBuyUserInfo($data['buy_id']);
        if(empty($buyer))
        {
            return Tool::returnJson([],405,"买手账号不存在");
        }
//        $buy_account = $this->RBuyUserAcountAccess->getBuyUserAccount($data['buy_id']);
//        if(empty($buy_account))
//        {
//            return Tool::returnJson([],406,"买手账号信息不存在");
//        }
        $task_order = [];
        //可提现本金
        $ava_refund_amount = 0;
        //可提现本金笔数
        $ava_count = 0;
        //待返还本金金额
        $waiting_refund_amount = 0;
        //待返还本金笔数
        $waiting_count = 0;
        //垫付本金待平台返款
        $total_refund_amount = 0;
        //垫付本金待平台返款  笔
        $total_count = 0;
        if($data['apply_status'] == 3)
        {
            //可提现
            $task_order = $this->RTaskOrderAccess->getTaskOrderStatus($data['buy_id'],8);
            if(count($task_order)>0)
            {
                foreach ($task_order as &$item)
                {
                    $ava_refund_amount += $item['refund_amount'];
                    $item['confirm_time'] = !empty($item['confirm_time']) ? date('Y-m-d H:i:s',$item['confirm_time']) : '--';
                    $item['apply_success_time'] = !empty($item['apply_success_time']) ? date('Y-m-d H:i:s',$item['apply_success_time']) : '--';
                }
            }
            $ava_count = count($task_order);
            $waiting_refund_arr = $this->RTaskOrderAccess->getTaskOrderRefundSum($data['buy_id'],7);
            $waiting_refund_amount = isset($waiting_refund_arr['total_refund_amount']) ? $waiting_refund_arr['total_refund_amount'] : 0;
            $waiting_count = $this->RTaskOrderAccess->getTaskOrderStatusCount($data['buy_id'],7);
            $total_refund_arr = $this->RTaskOrderAccess->getTaskOrderRefundSum($data['buy_id'],"2,3,4,5,6,7,9");
            $total_refund_amount = isset($total_refund_arr['total_refund_amount']) ? $total_refund_arr['total_refund_amount'] : 0;
            $total_count = $this->RTaskOrderAccess->getTaskOrderStatusCount($data['buy_id'],"2,3,4,5,6,7,9");

        }else if($data['apply_status'] == 2){
            $task_order = $this->RTaskOrderAccess->getTaskOrderStatus($data['buy_id'],7);
            if(count($task_order)>0)
            {
                foreach ($task_order as $item)
                {
                    $waiting_refund_amount += $item['refund_amount'];
                    $item['confirm_time'] = !empty($item['confirm_time']) ? date('Y-m-d H:i:s',$item['confirm_time']) : '--';
                    $item['apply_success_time'] = !empty($item['apply_success_time']) ? date('Y-m-d H:i:s',$item['apply_success_time']) : '--';
                }
            }
            $waiting_count = count($task_order);
            $ava_refund_arr = $this->RTaskOrderAccess->getTaskOrderRefundSum($data['buy_id'],8);
            $ava_refund_amount = isset($ava_refund_arr['total_refund_amount']) ? $ava_refund_arr['total_refund_amount'] : 0;
            $ava_count = $this->RTaskOrderAccess->getTaskOrderStatusCount($data['buy_id'],8);
            $total_refund_arr = $this->RTaskOrderAccess->getTaskOrderRefundSum($data['buy_id'],"2,3,4,5,6,7,9");
            $total_refund_amount = isset($total_refund_arr['total_refund_amount']) ? $total_refund_arr['total_refund_amount'] : 0;
            $total_count = $this->RTaskOrderAccess->getTaskOrderStatusCount($data['buy_id'],"2,3,4,5,6,7,9");
        }else if($data['apply_status'] ==1)
        {
            $task_order = $this->RTaskOrderAccess->getTaskOrderStatus($data['buy_id'],"2,3,4,5,6,7,9");
            if(count($task_order) >0)
            {
                foreach ($task_order as $item)
                {
                    $total_refund_amount += $item['refund_amount'];
                    $item['confirm_time'] = !empty($item['confirm_time']) ? date('Y-m-d H:i:s',$item['confirm_time']) : '--';
                    $item['apply_success_time'] = !empty($item['apply_success_time']) ? date('Y-m-d H:i:s',$item['apply_success_time']) : '--';
                }
            }
            $total_count = count($task_order);
            $waiting_refund_arr = $this->RTaskOrderAccess->getTaskOrderRefundSum($data['buy_id'],7);
            $waiting_refund_amount = isset($waiting_refund_arr['total_refund_amount']) ? $waiting_refund_arr['total_refund_amount'] : 0;
            $waiting_count = $this->RTaskOrderAccess->getTaskOrderStatusCount($data['buy_id'],7);
            $ava_refund_arr = $this->RTaskOrderAccess->getTaskOrderRefundSum($data['buy_id'],8);
            $ava_refund_amount = isset($ava_refund_arr['total_refund_amount']) ? $ava_refund_arr['total_refund_amount'] : 0;
            $ava_count = $this->RTaskOrderAccess->getTaskOrderStatusCount($data['buy_id'],8);
        }
        //统计总的待返款


        //获取提现信息
        $band_bank = $this->RBankAccess->getBuyUserBankAccount($data['buy_id']);
        return Tool::returnJson([
            "task_order"=> $task_order,
            "bank" => $band_bank,
            "ava_refund_amount" => $ava_refund_amount,
            "ava_count" => $ava_count,
            "waiting_refund_amount" => $waiting_refund_amount,
            "waiting_count" => $waiting_count,
            "total_refund_amount" => $total_refund_amount,
            "total_count" => $total_count,
        ],200,"成功");
    }

}